import crypto from 'crypto';
import axios from 'axios';

export const qwPicMsg = async (imageUrl) => {
	const res = (await axios.get(imageUrl, { responseType: 'arraybuffer' }))
		.data;
	if (res) {
		const buffer = Buffer.from(res, 'binary');
		const md5 = crypto.createHash('md5').update(buffer).digest('hex');
		const base64 = buffer.toString('base64');
		// console.log('MD5:', md5);
		// console.log('Base64:', base64);

		// qwMsg({
		// 	msgtype: 'news',
		// 	news: {
		// 		articles: [
		// 			{
		// 				title: '微信机器人登录',
		// 				description: '扫描二维码登录微信机器人',
		// 				url: imageUrl,
		// 				picurl: imageUrl,
		// 			},
		// 		],
		// 	},
		// });
		qwMsg({
			msgtype: 'image',
			image: {
				base64,
				md5,
			},
		});
	}
};

export const qwMsg = async (data) => {
	if (typeof data == 'string') {
		data = {
			msgtype: 'markdown',
			markdown: {
				content: data,
			},
		};
	}
	const res = await axios.request({
		method: 'POST',
		url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send',
		params: {
			key: 'c3ed9c2d-9a35-42aa-816e-e3ecc09df82d',
			debug: '1',
		},
		headers: { 'content-type': 'application/json' },
		data,
	});
	if (res.data && res.data.errcode == 0) {
		return true;
	}
	return false;
};
